package com.sh.sh_ai_agent.app;

import com.sh.sh_ai_agent.advisor.MyLoggerAdvisor;
import com.sh.sh_ai_agent.chatmemory.FileBaseChatMemory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import java.util.List;

import static com.sh.sh_ai_agent.constont.SystemPrompt.LOVER_EXPERT;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {

    // ChatClient 是构建聊天对话的入口
    private final ChatClient chatClient;
    private final ChatMemory chatMemory;


    // 注入本地向量数据库（用于 RAG）
    @Resource
    private VectorStore loveAppVectorStore;
    // 注入基于云服务的 RAG advisor
    @Resource
    private Advisor loveAppRagCloudAdvisor;
    // 注入 pgVector 的向量知识库
    //    @Resource
    //    private VectorStore pgVectorVectorStore;
    // 注入所有可用的工具函数（用于 Tool-Calling）
    @Resource
    private ToolCallback[] allTools;
    // 注入基于 ToolCallbackProvider 的工具（可动态注册）
    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    // 构造函数，传入 ChatModel（如 OpenAI、DashScope 等），用于构建 ChatClient 实例
    public LoveApp(ChatModel dashscopeChatModel) {
        // 使用基于文件的对话记忆系统
        String fileDir = System.getProperty("user.dir") + "/chat_memory";
//        FileBaseChatMemory chatMemory = new FileBaseChatMemory(fileDir);
        this.chatMemory = new InMemoryChatMemory();
        // 构建 ChatClient，设置默认 system 提示词和默认的记忆 advisor
        this.chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(LOVER_EXPERT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory) // 对话记忆管理
                )
                .build();
    }

    // 流式响应聊天（适用于前端逐字打印的场景）
    public Flux<String> doChatByStream(String message, String chatId) {
        log.info("当前对话ID: {}，用户输入：{}", chatId, message);
        Flux<String> content = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .advisors(
                        new MessageChatMemoryAdvisor(chatMemory)
//                        new MyLoggerAdvisor(),                           // ✅ 日志
//                        new QuestionAnswerAdvisor(loveAppVectorStore)   // ✅ 知识库 advisor
                )
                .stream()
                .content()
                .doOnNext(res -> log.info("收到响应式回复: {}", res)); // ✅ 在不消费流的情况下打印日志; // 以流的方式返回内容
        // 打印每一段流式响应
//        content.subscribe(res -> log.info("收到响应式回复: {}", res));
        return content;
    }

    // 普通对话，返回字符串结果，适用于传统聊天
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message) // 用户输入
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) // 会话ID
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)) // 记忆检索数
                .advisors(  new MessageChatMemoryAdvisor(chatMemory),  // ✅ 这里也别漏
                        new MyLoggerAdvisor())
                .call()
                .chatResponse(); // 执行并返回结果
        String content = response.getResult().getOutput().getText(); // 提取回复内容
        log.info("收到回复: {}", content);
        return content;
    }

    // 结构化输出对话结果为 LoveReport（包含标题与建议列表）
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .system(LOVER_EXPERT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class); // 将回复反序列化为 LoveReport
        return loveReport;
    }

    // 使用 RAG 的聊天方式（向量检索增强问答）
    public String doChatWithRag(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                // 以下三种方式任选一种
//                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
//                .advisors(loveAppRagCloudAdvisor)
//                .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
//                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore, "已婚"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        return content;
    }
    // 使用工具调用的对话方式（支持插件式工具）
    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools) // 加载全部工具
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }
    // 与上类似，使用 ToolCallbackProvider 动态注册调用工具
    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider) // 动态提供工具
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    // 自定义结构化输出的数据结构
    public record LoveReport(String title, List<String> suggestions) {
    }
}
